
$(function() {
    var setting = {
    	async: {
    		type: 'post',
    		dataType:'json',
    		dataFilter: dataFilter ,
    		autoParam:["orgId"],
    		url: ctx + '/admin/admin/organizations/manager/tree',
    		enable: true
    	},
    	check:{
    		enable: true,
    		chkboxType :{ "Y" : "", "N" : "" }
    	},
    	view: {
    		dblClickExpand: true,
    		showLine: false,
    		selectedMulti: true,
    		expandSpeed:"",
			addHoverDom: addHoverDom,
			removeHoverDom: removeHoverDom
    	},
    	edit: {
			enable: false
		},
    	data: {
    		key:  {
    			checked: 'checked',
    			children: 'children' ,
    			name: 'orgName' ,
    			title:'description' ,
    			url: 'url'	
    		},
    		simpleData: {
    			enable:true,
    			idKey: "orgId",
    			pIdKey: "parentId",
    			rootPId: ""
    		}
    	},
    	callback: {
    		beforeClick: beforeClick
    	}
    };

    function dataFilter (treeId, parentNode, data){
    	console.debug('dataFilter is  ' , treeId, parentNode, data) ;
    	
    	if (!data || data.code != 1) return null;
    	var childNodes = data.data ;
    	for (var i=0, l=childNodes.length; i<l; i++) {
    		childNodes[i].isParent = true;
    	}
    	
    	return childNodes;
    }
    function beforeClick(treeId, treeNode) {
    	/* if (!treeNode.isParent) {
    		alert("请选择父节点");
    		return false;
    	} else {
    		return true;
    	} */
    	seclectNode = treeNode ;
	    	return true;
    }

    function refreshNode(treeId, treeNode) {
    	var zTree = $.fn.zTree.getZTreeObj(tree) ;
    	var type = "refresh" ;
    	var silent = true ;
    	if (!treeNode) {
    		var msg = "<h4><span class='danger'>要选择一个节点才能刷新哦!</span></h4>" ;
			$('#alertModal .modal-body').html(msg) ;
			$('#alertModal').modal({
				backdrop: 'static' ,
				show: true
			}) ;
			return false ;
    	}
		zTree.reAsyncChildNodes(treeNode, type, silent);
//		if (!silent) zTree.selectNode(treeNode);
    }
    
    function addHoverDom(treeId, treeNode) {
    	console.debug('addHoverDom is  ' , treeId) ;
		var sObj = $("#" + treeNode.tId + "_span");
		
		if (treeNode.editNameFlag || $("#refreshBtn_"+treeNode.tId).length>0) return;
	
		var refreshStr = "<span class='button refresh' id='refreshBtn_" + treeNode.tId
		+ "' title='刷新节点' onfocus='this.blur();'></span>";
		
		sObj.after(refreshStr);
		
		var refreshBtn = $("#refreshBtn_"+treeNode.tId);
		/**刷新节点*/
		if (refreshBtn) refreshBtn.bind("click", function(){
			refreshNode(treeId, treeNode) ;
			return false;
		});
	};
	function removeHoverDom(treeId, treeNode) {
		$("#refreshBtn_"+treeNode.tId).unbind().remove();
	};
    
    /*************初始化*********************************/
    
    $.fn.zTree.init($("#" + tree), setting);
	
});

